package org.example.carplatoon.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
//import com.sun.org.apache.xerces.internal.impl.xpath.XPath;
import lombok.extern.slf4j.Slf4j;
import org.example.carplatoon.common.R;
import org.example.carplatoon.dto.UseEmp;
import org.example.carplatoon.entity.car;
import org.example.carplatoon.entity.carBind;
import org.example.carplatoon.entity.employee;
import org.example.carplatoon.entity.user;
import org.example.carplatoon.service.carBindService;
import org.example.carplatoon.service.carService;
import org.example.carplatoon.service.employeeService;
import org.example.carplatoon.service.userService;
import org.example.carplatoon.utils.JwtUtils;
import org.example.carplatoon.utils.SMSUtils;
import org.example.carplatoon.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RequestMapping
@RestController
public class userController {

    @Autowired
    private userService userService;

    @Autowired
    private carService carService;

    @Autowired
    private carBindService carBindService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private employeeService employeeService;

    @Value("${car.path}")
    private String basePath;

    /**
     * 多次查询数据库，判断是否存在重复的userName，email，phoneNum，idNumber，返回重复信息
     */
    private String validateExistingData(Long id, String userName, String email, String phoneNum, String idNumber) {
        Map<String, String> fieldsToCheck = new LinkedHashMap<>(); // 保持插入顺序的映射
        fieldsToCheck.put(userName, "当前用户名已存在");
        fieldsToCheck.put(email, "当前邮箱已存在");
        fieldsToCheck.put(phoneNum, "当前手机号已存在");
        fieldsToCheck.put(idNumber, "当前身份证号已存在");

        String errorMessage = null;
        for (Map.Entry<String, String> entry : fieldsToCheck.entrySet()) {
            String fieldValue = entry.getKey();
            String errorMessageForField = entry.getValue();

            if (StringUtils.isNotEmpty(fieldValue)) {
                LambdaQueryWrapper<user> queryWrapper = new LambdaQueryWrapper<>();
                if (fieldValue.equals(userName)) {
                    queryWrapper.eq(user::getUserName, userName);
                } else if (fieldValue.equals(email)) {
                    queryWrapper.eq(user::getEmail, email);
                } else if (fieldValue.equals(phoneNum)) {
                    queryWrapper.eq(user::getPhoneNum, phoneNum);
                } else if (fieldValue.equals(idNumber)) {
                    queryWrapper.eq(user::getIdNumber, idNumber);
                }

                // 排除指定ID的员工数据
                if (id != null) {
                    queryWrapper.ne(user::getId, id);
                }

                int existingUser = userService.count(queryWrapper);
                if (existingUser > 0) {
                    errorMessage = errorMessage != null ? errorMessage + "，" + errorMessageForField : errorMessageForField;
                    // 如果需要在第一个冲突时就返回，可以直接使用 return errorMessageForField;
                }
            }
        }
        return errorMessage;
    }

    /**
     * 只查询一次数据库，判断是否存在重复的userName，email，phoneNum，idNumber，返回错误不精确
     */
//    private String validateExistingData(Long id, String userName, String email, String phoneNum, String idNumber) {
//        LambdaQueryWrapper<user> queryWrapper = new LambdaQueryWrapper<>();
//        // 如果传入了ID，则排除指定ID的员工数据
//        if (id != null) {
//            queryWrapper.ne(user::getId, id);
//        }
//
//        queryWrapper.and(i ->
//                i.eq(StringUtils.isNotEmpty(userName), user::getUserName, userName)
//                        .or()
//                        .eq(StringUtils.isNotEmpty(email), user::getEmail, email)
//                        .or()
//                        .eq(StringUtils.isNotEmpty(phoneNum), user::getPhoneNum, phoneNum)
//                        .or()
//                        .eq(StringUtils.isNotEmpty(idNumber), user::getIdNumber, idNumber)
//        );
//
//        int existingUser = userService.count(queryWrapper);
//        if (existingUser > 0) {
//            return "输入信息已存在";
//        }
//
//        return null;
//    }


    /**
     * 根据userId返回车辆所属人信息
     *
     * @param userId
     * @return
     */
    @GetMapping("/getCarUserInfo")
    @Transactional
    public R<user> getCarUserInfo(@RequestParam("userId") long userId) {

        user user = userService.getById(userId);
        if (user == null) {
            return R.error("未查询到该用户相关信息");
        }
        //todo:暂时固定用户头像src，后续需前端上传图片保存到服务器
//        String avatar = user.getAvatar();
//        user.setAvatar(basePath + avatar);
        return R.success("success", user);
    }

    @GetMapping("/getCode")
    @Transactional
    public R getCode(String userName, String email, String name) {
        if (StringUtils.isEmpty(userName)) {
            return R.error("验证码发送失败，用户名不能为空");
        }
        if (StringUtils.isEmpty(email)) {
            return R.error("验证码发送失败，邮箱不能为空");
        }
        if (StringUtils.isEmpty(name)) {
            return R.error("验证码发送失败，姓名不能为空");
        }
        String errorMessage = validateExistingData(null, userName, email, null, null);
        if (errorMessage != null) {
            return R.error(errorMessage);
        }

        String code = ValidateCodeUtils.generateValidateCode(6).toString();
        log.info("code={}", code);
        //调用方法发送短信
        SMSUtils.sendEmail(email, userName, name, code);

        //将生成的验证码缓存到Redis中，并且设置有效期为5分钟
        redisTemplate.opsForValue().set(email, code, 5, TimeUnit.MINUTES);
        redisTemplate.opsForValue().set(userName, code, 5, TimeUnit.MINUTES);
        redisTemplate.opsForValue().set(name, code, 5, TimeUnit.MINUTES);

        return R.success("验证码发送成功", null);

    }

    @PostMapping("/register")
    @Transactional
    public R register(@RequestBody Map<String, Object> map) {
//        log.info(map.toString());

        String email = map.get("email").toString();
        String userName = map.get("userName").toString();
        String name = map.get("name").toString();
        String verCode = map.get("verCode").toString();
        String passWord = map.get("passWord").toString();
        if (StringUtils.isEmpty(passWord) || StringUtils.isEmpty(email) || StringUtils.isEmpty(userName) || StringUtils.isEmpty(verCode) || StringUtils.isEmpty(name)) {
            return R.error("输入信息不能为空");
        }
        passWord = DigestUtils.md5DigestAsHex(passWord.getBytes());

        String errorMessage = validateExistingData(null, userName, email, null, null);
        if (errorMessage != null) {
            return R.error(errorMessage);
        }

//        从redis中获取缓存的验证码
        Object codeInEmail = redisTemplate.opsForValue().get(email);
        Object codeInUserName = redisTemplate.opsForValue().get(userName);
        Object codeInName = redisTemplate.opsForValue().get(name);
//        比对成功，进行注册功能
        if (codeInEmail != null && codeInEmail.equals(verCode) && codeInEmail.equals(codeInUserName) && codeInEmail.equals(codeInName)) {
            user user = new user();
            user.setEmail(email);
            user.setName(name);
            user.setUserName(userName);
            user.setPassWord(passWord);
            user.setStatus(1);
            //todo:暂时固定用户头像src，后续需前端上传图片保存到服务器
            user.setAvatar("/images/test.jpg");
            userService.save(user);
            return R.success("注册成功", null);
        }
        return R.error("注册失败");
    }

    @PostMapping("/userLogin")
    @Transactional
    public R userLogin(@RequestBody Map<String, Object> map) {
        log.info(map.toString());
        String userName = map.get("userName").toString();
        String passWord = map.get("passWord").toString();

        if (passWord.isEmpty() || userName.isEmpty()) {
            return R.error("信息不能为空");
        }

        passWord = DigestUtils.md5DigestAsHex(passWord.getBytes());

        LambdaQueryWrapper<user> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(user::getUserName, userName);
        user user = userService.getOne(queryWrapper);

        if (user == null) {
            return R.error("未查询到该用户");
        }
        if (user.getStatus() == 0) {
            return R.error("该用户已被禁用");
        }

        if (!user.getPassWord().equals(passWord)) {
            return R.error("用户名或密码错误");
        }
        Map<String, Object> tmp = new HashMap<>();
        tmp.put("id", String.valueOf(user.getId()));
        tmp.put("userName", user.getUserName());
        tmp.put("sex", user.getSex());
        tmp.put("phoneNum", user.getPhoneNum());
        tmp.put("birthDate", user.getBirthDate());
        tmp.put("idNumber", user.getIdNumber());
        tmp.put("address", user.getAddress());
        tmp.put("avatar", user.getAvatar());
        tmp.put("email", user.getEmail());
        tmp.put("name", user.getName());

        String token = JwtUtils.createToken(tmp);
        tmp.put("jwt", token);

        return R.success("登录成功", tmp);
    }

    @PostMapping("/updateUserInfo")
    public R<user> updateUserInfo(@RequestBody user u) {
        Long id = u.getId();

        user user = userService.getById(id);
        if (user == null) {
            return R.error("该用户不存在");
        }

        LambdaQueryWrapper<carBind> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(carBind::getUserId, id);
        carBind bind = carBindService.getOne(queryWrapper);
        if (bind != null) {
            return R.error("该用户正在车队中，无法修改");
        }
        String userName = u.getUserName();
        String phoneNum = u.getPhoneNum();
        String idNumber = u.getIdNumber();
        String errorMessage = validateExistingData(id, userName, null, phoneNum, idNumber);
        if (errorMessage != null) {
            return R.error(errorMessage);
        }
        if (phoneNum.length() != 11 || idNumber.length() != 18) {
            return R.error("请输入正确的手机号或身份证号码");
        }
        //todo:暂时固定用户头像src，后续需前端上传图片保存到服务器
        u.setAvatar("/images/test.jpg");
        userService.updateById(u);
        user newUser = userService.getById(id);
        return R.success("更新成功", newUser);
    }

    @PostMapping("/changePassWord")
    public R changePassWord(@RequestBody Map<String, Object> map) {
        String id = (String) map.get("id");
        String oldPassWord = (String) map.get("oldPassWord");
        String newPassWord = (String) map.get("newPassWord");
        user user = userService.getById(id);
        if (user == null) {
            return R.error("该用户不存在");
        }
        oldPassWord = DigestUtils.md5DigestAsHex(oldPassWord.getBytes());
        if (!oldPassWord.equals(user.getPassWord())) {
            return R.error("原密码错误");
        }
        newPassWord = DigestUtils.md5DigestAsHex(newPassWord.getBytes());
        user.setPassWord(newPassWord);
        userService.updateById(user);
        return R.success("密码修改成功", null);
    }

    @GetMapping("/getAllUser")
    @Transactional
    public R<Page> getGetAllUser(int page, int pageSize, String name, String phoneNum) {
        LambdaQueryWrapper<user> userLambdaQueryWrapper = new LambdaQueryWrapper<>();

        userLambdaQueryWrapper.likeRight(StringUtils.isNotEmpty(name), user::getName, name)
                .likeRight(StringUtils.isNotEmpty(phoneNum), user::getPhoneNum, phoneNum);

        // 如果 name 和 phoneNum 都为空，则不添加任何查询条件
        if (StringUtils.isEmpty(name) && StringUtils.isEmpty(phoneNum)) {
            userLambdaQueryWrapper = null;
        }

        Page<user> pageInfo = new Page<>(page, pageSize);

        Page<user> pageResult = userService.page(pageInfo, userLambdaQueryWrapper);
//        todo:暂时固定图片src
        for (user record : pageResult.getRecords()) {
            String avatar = record.getAvatar();
            record.setAvatar(avatar);
        }

        return R.success("获取信息成功", pageResult);
    }

    @PostMapping("/changeStatus")
    @Transactional
    public R<String> changeStatus(@RequestBody UseEmp useEmp) {

        int who = useEmp.getWho();
        int status = useEmp.getStatus();
        long id = useEmp.getId();
        if (who == 0) {
            LambdaQueryWrapper<user> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(user::getId, id);
            user one = userService.getOne(lambdaQueryWrapper);
            if (one == null) {
                return R.error("未查询到该用户信息");
            }
            LambdaQueryWrapper<carBind> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(carBind::getUserId, one.getId());
            carBind carBind = carBindService.getOne(queryWrapper);
            if (carBind != null) {
                return R.error("用户正在车队中，无法删除");
            }
            one.setStatus(status);
            userService.updateById(one);

        } else {
            LambdaQueryWrapper<employee> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(employee::getId, id);
            employee one = employeeService.getOne(lambdaQueryWrapper);
            if (one == null) {
                return R.error("未查询到该管理员信息");
            }
            if (one.getUserName().equals("admin")) {
                return R.error("超级管理员无法禁用");
            }
            one.setStatus(status);
            employeeService.updateById(one);
        }

        return R.success("修改成功", null);


    }


}
